#include "Camera.h"


Camera::Camera(std::string name)
	:Node(name)
	,m_iSpeed(0.005)
{
	D3DXMatrixIdentity(&m_matView);
}


Camera::~Camera(void)
{
}

void Camera::KeyboardUpdate( KeyboadMsg msg )
{
	switch(msg)
	{
	case KMsg_W_DOWN:
		walk(Forward);
		break;
	case KMsg_S_DOWN:
		walk(Back);
		break;
	case KMsg_A_DOWN:
		walk(Left);
		break;
	case KMsg_D_DOWN:
		walk(Right);
		break;
	}
}

void Camera::init()
{
	//make the camera listen the keyboard
	KeyboardSubject::Instance()->AddKeyboardListener(this);
	//make the camera listen the mouse
	MouseSubject::Instance()->AddMouseListener(this);

	
}

void Camera::MouseUpdate( MouseMsg msg,const Point& oldPoint,const Point& currPoint )
{
	switch (msg)
	{
	case MMsg_Move:
		MouseMove(oldPoint,currPoint);
		break;
	}
}

void Camera::MouseMove( const Point& oldPoint,const Point& currPoint )
{
	if(!MessageQueryer::Instance()->MouseLeftButtonIsPress())
		return ;

	int dx,dy;
	dx = currPoint.x - oldPoint.x;
	dy = currPoint.y - oldPoint.y;

	pitch(dy * 0.0087266f);
	yaw(dx * 0.0087266f);

	UpdateViewMatrix();
}

D3DXMATRIX Camera::GetView()
{
	return m_matView;
}

void Camera::UpdateViewMatrix()
{
	D3DXMatrixLookAtLH(&m_matView, &m_vPostion, &(m_vOrientation+m_vPostion), &m_vUp);
	GlobalMessage::Instance()->SetViewMatrix(m_matView);
}

void Camera::walk( Direction direction )
{
	m_iSpeed = GlobalMessage::Instance()->GetTimeFromLastFrame()*40.0f;
	switch(direction)
	{
	case Forward:
		m_vPostion += m_iSpeed*m_vOrientation;
		break;
	case Back:
		m_vPostion -= m_iSpeed*m_vOrientation;
		break;
	case Left:
		m_vPostion -= m_iSpeed*m_vRight;
		break;
	case Right:
		m_vPostion += m_iSpeed*m_vRight;
		break;
	}

	UpdateViewMatrix();
}
